<template>
  <div class="GoodsClassify">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="分类名称" :label-col="{ span: 5}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input
                placeholder="请输入"
                v-decorator="[
          'cname',
          {rules: [{ required: true, message: '请输入分类名称!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="16" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="getfindPage" :style="{ marginRight: '1%' }">查询</a-button>
            <a-button type="dashed" @click="listExport" :style="{ marginRight: '1%' }">导出</a-button>
            <a-button htmlType="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card style="margin-top:2%">
      <router-link to="/home/goodsadmin/goodsclassify/goodsnewclassify">
        <a-button type="primary" icon="plus">新建</a-button>
      </router-link>

      <a-table
        style="margin-top:2%"
        :columns="columns"
        :dataSource="data"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :rowKey="record => record.id"
      >
        <template slot="operate" slot-scope="text,record">
          <span class="blue" @click="showModal(text,record)">编辑</span>
          <span
            class="red"
            @click="record.goodsNumber>0?noDeleteConfirm():showDeleteConfirm(text,record)"
          >删除</span>
          <!-- //编辑的弹出框 -->
          <a-modal
            title="编辑商品分类"
            :visible="visible"
            @ok="handleOk"
            @cancel="handleCancel"
            v-model="visible"
          >
            <template slot="footer">
              <a-button key="back" @click="handleCancel">取消</a-button>
              <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
            </template>

            <a-form :form="form">
              <a-form-item label="分类名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                <a-input
                  style="width: 100%"
                  placeholder="请输入"
                  v-decorator="[
          'classifyName',
          {rules: [{ required: true, message: '请输入分类名称!' }]} 
        ]"
                />
              </a-form-item>

              <!-- <a-form-item
                label="上级分类"
                :label-col="{ span: 5 }"
                :wrapper-col="{ span: 12 }"
                v-show="isSelect"
              >
                <a-select
                  @select="select"
                  @change="handleChange"
                  @dropdownVisibleChange="dropdownVisibleChange"
                  style="width: 100%"
                  v-decorator="[
          'superiorClassify',
          {rules: [{ required: true, message: '请选择上级分类!' }]}
        ]"
                  placeholder="请设置商品品牌"
                >
                  <a-select-option
                    v-for="item in selectdata"
                    :key="item.id"
                    :value="item.name"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item
              >-->
            </a-form>
          </a-modal>
          <!-- 编辑的弹出框 -->
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
const columns = [
  {
    title: "分类名称",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "cname" },
    align: "center"
  },

  {
    title: "商品数",
    dataIndex: "goodsNumber",
    key: "number",
    scopedSlots: { customRender: "goodsNum" },
    align: "center"
  },
  {
    title: "序号",
    dataIndex: "sort",
    key: "sort",
    scopedSlots: { customRender: "number" },
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    scopedSlots: { customRender: "creationTime" },
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "",
    key: "operate",
    scopedSlots: { customRender: "operate" },
    align: "center"
  }
];
export default {
  name: "GoodsClassify",
  data() {
    return {
      form: this.$form.createForm(this),
      rangeConfig: {
        rules: [
          { type: "array", required: true, message: "Please select time!" }
        ]
      },
      data: [],
      columns,
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["2", "4", "8", "10", "12"],
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        },
        pageSize: 5,
        defaultCurrent: 5,
        current: 1,
        total: 500
      },
      loading: false,
      visible: false,
      selectdata: [],
      isSelect: false
    };
  },
  watch: {},
  computed: {},
  created() {
    this.listInit();
    this.getfindPage();
  },
  methods: {
    select(value, option) {
      // console.log(value,option);
      // this.editValue = value;
    },
    dropdownVisibleChange(open) {
      // console.log(open);
    },
    handleChange(value, option, index) {
      console.log(`selected ${value}`);
    },
    handleSearch(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {
        console.log("error", error);
        console.log("Received values of form: ", values);
      });
    },
    callback(key) {
      console.log(key);
    },
    showModal(text, record) {
      this.visible = true;
      this.editId = record.id;
      this.editInit(text, record);
    },
    handleOk(e) {
      this.visible = false;
      var values = this.form.getFieldsValue();
      console.log(values.classifyName);
      this.listEdit(values.classifyName);
      console.log(this.formatter(values.superiorClassify, this.selectdata));
    },
    handleCancel(e) {
      this.visible = false;
    },
    showDeleteConfirm(text) {
      var that = this;
      this.delId = text.id;
      this.$confirm({
        title: "确认删除",
        content: "确认要删除此商品分类吗？",
        okText: "确定",
        cancelText: "取消",
        iconType: "close-circle",
        onOk() {
          that.listDel(that.delId);
        },
        onCancel() {}
      });
    },
    noDeleteConfirm() {
      this.$message.error("错误的操作,分类下有商品");
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.getfindPage();
    },
    // 初始化分页
    listInit() {
      this.axios
        .post(this.baseUrl + "/goodsCategory/listInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 查询商品分类列表
    getfindPage() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/goodsCategory/findPageListByCondition", {
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          name: values.cname,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        })
        .catch(error => {
          console.log(error);
        });
    },

    formatter(text, list) {
      if (Number(text)) {
        for (let i = 0; i < list.length; i++) {
          if (text == list[i].id) {
            return list[i].name;
          }
        }
      } else {
        for (let i = 0; i < list.length; i++) {
          if (text == list[i].name) {
            return list[i].id;
          }
        }
      }
    },

    //编辑商品分类初始化
    editInit(text, record) {
      // console.log(text);
      this.axios
        .post(this.baseUrl + "/goodsCategory/editInit", {
          id: this.editId,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          this.editParentId = response.data.data.parentId;
          if (this.editParentId != null) {
            this.isSelect = true;
          } else {
            this.isSelect = false;
          }
          this.selectdata = response.data.data.list;
          // console.log(this.formatter(this.editParentId, this.selectdata));
          this.form.setFieldsValue({
            classifyName: record.name,
            superiorClassify: this.formatter(this.editParentId, this.selectdata)
          });
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 编辑弹出框数据
    listEdit(name) {
      this.axios
        .post(this.baseUrl + "/goodsCategory/edit", {
          name: name,
          id: this.editId,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          this.getfindPage();
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 删除操作
    listDel(id) {
      this.axios
        .post(this.baseUrl + "/goodsCategory/del", {
          id: id,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          if (response.data.code == 0) {
            this.$message.success("删除成功");
            this.getfindPage();
          }
          if (response.data.code == -1) {
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 导出文件
    listExport() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(
          this.baseUrl + "/goodsCategory/export",
          {
            name: values.cname,
            loginToken: this.$store.state.loginToken
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          // console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "商品分类表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  mounted() {
    // this.getfindPage();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.AfterSaleIndent {
  width: 100%;
}
</style>
